package com.saltedfish.tool.util;

import android.content.Context;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;

import androidx.core.content.ContextCompat;

import com.saltedfish.tool.R;

public class CharUtils {
    /**
     * 设置指定字体高亮
     *
     * @return CharSequence型字符串
     */
    public static CharSequence getHighLightText(Context context, String text, String keyword) {
        SpannableStringBuilder style = new SpannableStringBuilder(text);
        if (!keyword.isEmpty()) {
            int base = 0;//基准index，表示每一次进行字符串截取之后，新字符字符串的开始index相对于text原始字符串的位置
            int start;
            do {
                start = text.indexOf(keyword);
                int end;
                if (start >= 0) {
                    end = start + keyword.length();
                    style.setSpan(
                            new ForegroundColorSpan(ContextCompat.getColor(context, R.color.color_004DFF)),
                            base + start, base + end,
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    text = text.substring(end);
                    base += end;
                }
            } while (start >= 0 && text.length() > 0);
        }
        return style;
    }
}
